import React, { useState, useEffect } from 'react'
import ReactECharts from 'echarts-for-react'
import * as echarts from 'echarts'
import BlockTitle from '../../../../../framework/BlockTitle'
import SouyeApi from '../../../../../../utils/apis/SouyeApi'
import { resourcePath } from '../../../../../../utils/resource'

export default function Wxhxp() {
    const [chartData, setChartData] = useState([])
    const [loading, setLoading] = useState(true)
    const [total, setTotal] = useState(0)

    useEffect(() => {
        const fetchData = async () => {
            try {
                setLoading(true)
                const response = await SouyeApi.cztzl_find("危险化学品")
                if (response && response.data?.length) {
                    setChartData(response.data)
                    const totalCount = response.data.reduce((sum, item) => sum + item.count, 0)
                    setTotal(totalCount)
                } else {
                    const defaultData = [
                        { cztxl: '加油加气站', count: 24 },
                        { cztxl: '化工园区', count: 1 }
                    ]
                    setChartData(defaultData)
                    setTotal(25)
                }
            } catch (error) {
                console.error('获取危险化学品数据失败:', error)
                const defaultData = [
                    { cztxl: '加油加气站', count: 24 },
                    { cztxl: '化工园区', count: 1 }
                ]
                setChartData(defaultData)
                setTotal(25)
            } finally {
                setLoading(false)
            }
        }
        
        fetchData()
    }, [])

    const getOption = () => {
        if (!chartData || chartData.length === 0) {
            return {}
        }

        const colors = ['#00E5A0', '#FFD700'] // 绿色和黄色
        
        const pieData = chartData.map((item, index) => ({
            name: item.cztxl,
            value: item.count,
            itemStyle: {
                color: colors[index % colors.length]
            }
        }))

        return {
            backgroundColor: 'transparent',
            title: {
                text: total.toString(),
                subtext: '总数（处）',
                left: 'center',
                top: 'center',
                textStyle: {
                    fontSize: 32,
                    fontWeight: 'bold',
                    color: '#ffffff'
                },
                subtextStyle: {
                    fontSize: 14,
                    color: '#ffffff',
                    lineHeight: 20
                }
            },
            tooltip: {
                trigger: 'item',
                backgroundColor: 'rgba(0, 0, 0, 0.8)',
                borderColor: '#00E5A0',
                borderWidth: 1,
                textStyle: {
                    color: '#ffffff'
                },
                formatter: function(params) {
                    const percent = ((params.value / total) * 100).toFixed(2)
                    return params.name + '：' + params.value + ' 处 (' + percent + '%)'
                }
            },
            legend: {
                orient: 'horizontal',
                bottom: 20,
                left: 'center',
                textStyle: {
                    color: '#ffffff',
                    fontSize: 12
                },
                itemWidth: 10,
                itemHeight: 10,
                formatter: function(name) {
                    const item = chartData.find(d => d.cztxl === name)
                    return name + ' ' + (item ? item.count : 0) + ' 处'
                }
            },
            series: [{
                type: 'pie',
                radius: ['42%', '50%'], // 稍微加粗圆环
                center: ['50%', '50%'],
                avoidLabelOverlap: false,
                label: {
                    show: false,
                    position: 'outside',
                    formatter: function(params) {
                        const percent = ((params.value / total) * 100).toFixed(2)
                        return percent + '%'
                    },
                    fontSize: 14,
                    fontWeight: 'bold',
                    color: '#ffffff'
                },
                labelLine: {
                    show: true,
                    lineStyle: {
                        color: '#ffffff'
                    }
                },
                emphasis: {
                    scale: true,
                    scaleSize: 5
                },
                data: pieData
            }]
        }
    }

    return (
        <div style={{
            width: '100%',
            overflow: 'hidden',
            position: 'relative'
        }}>
            <BlockTitle style={{
                marginBottom: 0,
                fontFamily: 'pmzd',
            }}>
                危险化学品
            </BlockTitle>
            
            <div style={{
                height: '300px',
                padding: '10px',
                position: 'relative',
                display: 'flex',
                justifyContent: 'center',
                alignItems: 'center'
            }}>
                {loading ? (
                    <div style={{
                        display: 'flex',
                        justifyContent: 'center',
                        alignItems: 'center',
                        height: '100%',
                        color: '#ffffff',
                        fontSize: '14px'
                    }}>
                        数据加载中...
                    </div>
                ) : (
                    <>
                        {/* 旋转的钟表装饰背景 */}
                        <div style={{
                            position: 'absolute',
                            width: '237px',
                            height: '237px',
                            backgroundImage: `url(${resourcePath.homeCirclePng})`,
                            backgroundSize: 'contain',
                            backgroundRepeat: 'no-repeat',
                            backgroundPosition: 'center',
                            animation: 'rotate 20s linear infinite',
                            zIndex: 1
                        }} />
                        
                        {/* ECharts圆环图 */}
                        <div style={{
                            position: 'relative',
                            width: '100%',
                            height: '100%',
                            zIndex: 2
                        }}>
                            <ReactECharts 
                                option={getOption()} 
                                style={{ height: '100%', width: '100%' }}
                                notMerge={true}
                                lazyUpdate={true}
                            />
                        </div>
                        
                        {/* CSS动画定义 */}
                        <style>
                            {`
                                @keyframes rotate {
                                    from {
                                        transform: rotate(0deg);
                                    }
                                    to {
                                        transform: rotate(360deg);
                                    }
                                }
                            `}
                        </style>
                    </>
                )}
            </div>
        </div>
    )
} 